package Matrix;

/**
 * 蛇形打印一个矩阵
 */
public class ZigzagPrintMatrix {
    public static void main(String[] args) {
        int[][] ints = {{1, 2}, {1, 2}};

        printMatrixZigZag(ints);
    }

    public static void printMatrixZigZag(int[][] matrix) {
        int ar = 0;
        int ac = 0;
        int br = 0;
        int bc = 0;
        int endR = matrix.length - 1;
        int endC = matrix[0].length - 1;

        boolean fromUp = false;

        while (ar != endR + 1) {
            printLevel(matrix, ar, ac, br, bc, fromUp);

            // 左上角开始一个点 先向右走，走到头，在向下走
            ar = ac == endC ? ar + 1 : ar;
            ac = ac == endC ? ac : ac + 1;
            // 左上角开始一个点 先向下走，走到头，在向右走
            bc = br == endR ? bc + 1 : bc;
            br = br == endR ? br : br + 1;
            fromUp = !fromUp;
        }
    }

    private static void printLevel(int[][] matrix, int a, int b, int c, int d, boolean fromUp) {

        if (fromUp) {
            while (a != c + 1) {
                System.out.println(matrix[a++][b--]);
            }
        } else {
            while (c != a - 1) {
                System.out.println(matrix[c--][d++]);
            }
        }
    }
}
